package com.zztt.logmask.common.utils;

import com.zztt.logmask.common.ConfigConst;
import com.zztt.logmask.common.MaskHandleDelegate;
import com.zztt.logmask.common.factory.DefaultMaskHandleFactory;
import com.zztt.logmask.common.handle.MaskHandle;

import java.util.List;

/**
 * 掩码处理开关的工具类
 */
public final class MaskHandleUtils {

    private static final MaskHandleDelegate MASH_HANDLE_DELEGATE = new MaskHandleDelegate();

    private MaskHandleUtils(){
        throw new RuntimeException("工具类不能被实例化!");
    }

    /**
     * 根据掩码是否开启  和 日志级别 来看是否对message进行处理
     * @param maskSwitch 掩码功能是否开启
     * @param level      日志级别信息
     * @param message    被处理的日志信息
     * @return
     */
    public static String maskHandleMessage(boolean maskSwitch,String level,String message){
        //判断掩码开关 和 日志级别都匹配的话 开启掩码处理
        if (maskSwitch) {
            if(ConfigConst.MASK_LEVEL.isEmpty() || ConfigConst.MASK_LEVEL.contains(level)){
                StringBuilder stringBuilder = new StringBuilder(message);
                MASH_HANDLE_DELEGATE.mask(stringBuilder);
                return stringBuilder.toString();
            }
        }
        return message;
    }

    /**
     * 设置多个掩码处理器  顺序根据配置文件中的顺序进行
     * @param maskHandles
     */
    public static void setMaskHandles(String maskHandles) throws Exception{
        if(StringUtils.isNotBlank(maskHandles)){
            List<String> maskHandleStrList = StringUtils.parseStr2List(maskHandles,ConfigConst.SPLIT_CHAR);
            for (String maskHandleStr : maskHandleStrList) {
                Class<?> maskHandleClass = Class.forName(maskHandleStr.trim());
                if (!MaskHandle.class.isAssignableFrom(maskHandleClass)){
                    throw new RuntimeException(maskHandleClass.getName() + " 未实现com.cupdata.zicon.logmask.common.handle.MaskHandle接口!");
                }
                MaskHandle maskHandle = (MaskHandle)maskHandleClass.newInstance();
                DefaultMaskHandleFactory.getInstance().registerMaskHandle(maskHandle);
            }
        }
    }

    /**
     * 设置 掩码处理器是否开启
     * @param maskHandlesEnabled
     */
    public static void setMaskHandlesEnabled(boolean maskHandlesEnabled){
        ConfigConst.MASK_SWITCH = maskHandlesEnabled;
    }
    /**
     * 设置 掩码处理器支持的日志级别
     * @param maskHandleSuportLevels
     */
    public static void setMaskHandleSuportLevels(String maskHandleSuportLevels){
        if(StringUtils.isNotBlank(maskHandleSuportLevels)){
            List<String> stringList = StringUtils.parseStr2List(maskHandleSuportLevels,ConfigConst.SPLIT_CHAR);
            ConfigConst.MASK_LEVEL.addAll(stringList);
        }
    }
}
